import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Dropdown, Menu, Icon, Popconfirm, message, Modal, Select, TreeSelect, Checkbox, Radio } from 'antd'
import _ from 'lodash'

import Ajax from 'lib/Ajax'
import AreaInput from 'components/areaInput'
import { getNewTreeData, findRowData, confirmDelete, validatorArea } from 'lib/fun'

const ButtonGroup = Button.Group;
const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;

class ModuleName extends Component {
	constructor(props) {
    super(props);
    
    this.state = {
      loading: false,
      visible: false,
      settingVisible: false,
      editType: "",
      rowdata: {},
      data: [],
    }
    // 翻页相关
    this.current = 1;   //当前第几页
    this.total = 10;   //总共多少页
    this.pageSize = 10;   //每页多少行
    this.search = {};
    this.select = {};
  }

  componentDidMount() {
    this.loadData();
  }

  componentWillReceiveProps(nextProps){
    var self = this;
    if(!_.isEqual(this.props.search, nextProps.search)||!_.isEqual(this.props.select, nextProps.select)&&nextProps.select.areaId){
      this.current = 1;
      this.search = nextProps.search;
      this.select = nextProps.select;
      self.loadData();
    }
  }

  pageOnChange = (page)=>{
    this.current = page;
    this.loadData();
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(((this.current-1)*this.pageSize+1)/pageSize);
    this.pageSize = pageSize;
    this.current = page;
    this.loadData();
  }

  loadData = ()=>{
    var self = this;
    self.setState({
      loading: true
    });
    Ajax({
      url: '/user/list',
      data: {
        "userId": this.search.userId,   //用户id
        "userAccount": this.search.userAccount,
        "userName": this.search.userName,   //用户名称
        "disabled": this.search.disabled == "2"||this.search.disabled == undefined?undefined:(this.search.disabled == "1"?true:false), //是否启用
        "areaId": this.select.areaId?this.select.areaId:"",  //机构编号
        "currentPage": self.current,  //请求页码
        "perPage": self.pageSize,   //每页数量
        "userType": 'typein'
      },
      success: function(data){
        self.total = data.totalCount;
        self.setState({
          loading: false,
          data: data.list
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  setting = (row)=>{
    this.setState({
      settingVisible: true,
      rowdata: row
    });
  }
  // 操作
  operate = (type, row)=>{
    if(type == 'edit'){
      this.setState({
        visible: true,
        editType: 'edit',
        rowdata: row
      });
    }else{
      this.setState({
        visible: true,
        editType: 'new'
      });
    }
  }

  editOk = (type, rowdata)=>{
    var self = this;
    if(type == 'edit'){
      var find = _.find(self.state.data, (item)=>{
        return item.userId == rowdata.userId
      });
      Object.assign(find, rowdata);
      self.setState({
        visible: false,
        rowdata: {},
        data: self.state.data
      });
      message.success('修改记录成功！');
    }else{
      self.state.data.unshift(rowdata);
      self.setState({
        visible: false,
        rowdata: {},
        data: self.state.data
      });
      message.success('增加记录成功！');
    }
  }
  editCancel = ()=>{
    this.setState({
      visible: false,
      rowdata: {}
    });
  }
  onClose = ()=>{
    this.setState({
      settingVisible: false,
      rowdata: {}
    });
  }

  doDelete = (id)=>{
    var self = this;
    confirmDelete(()=>{
      Ajax({
        url: '/user/delete',
        data: {
          "userId": id
        },
        success: function(data){
          // _.remove(self.state.data, function(d) {
          //   return d.userId == id
          // });
          // self.setState({
          //   data: self.state.data
          // });
          self.loadData();
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
      message.info('取消删除');
    });
  }
  
  render() {
    var pagination = {
      current: this.current,
      total: this.total,
      pageSize: this.pageSize,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      onShowSizeChange: this.showSizeChange,
      showTotal: total => `总共 ${total} 条`
    };
    
    const columns = [{
        title: '用户登录账号',
        dataIndex: 'userAccount'
      }, {
        title: '用户名称',
        dataIndex: 'userName'
      }, {
        title: '所属区划',
        dataIndex: 'areaName'
      }, {
        title: '电话号码',
        dataIndex: 'phone'
      }, {
        title: '用户状态',
        dataIndex: 'disabled',
        render: (text, record) => (<span>{!text?"启用":"禁用"}</span>)
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <Dropdown overlay={
              <Menu>
                <Menu.Item>
                  <a onClick={this.operate.bind(this, "edit", record)} href="javascript:;">编辑</a>
                </Menu.Item>
                <Menu.Item>
                  <a onClick={this.setting.bind(this, record)} href="javascript:;">设置角色</a>
                </Menu.Item>
                <Menu.Item>
                  <a href="javascript:;" onClick={this.doDelete.bind(this, record.userId)}>删除</a>
                </Menu.Item>
              </Menu>
            }>
              <a className="ant-dropdown-link" href="javascript:;">
                操作 <Icon type="down" />
              </a>
            </Dropdown>
          </span>
        )
    }];

    return (
    	<div>
        <div className="table-con no-expand">
          <Table
            columns={ columns }
            dataSource={ this.state.data }
            pagination={ pagination }
            loading={this.state.loading}
            rowKey="userId"
            title={() => (<div>
                            <Button type="primary" style={{marginRight: 15}} icon="plus" onClick={ this.operate.bind(this, 'new') }>新建</Button>
                            {/*<Button type="primary" icon="export">批量导入</Button>*/}
                          </div>)}
          />
        </div>
        <EditModule 
          visible={ this.state.visible }
          onOk={ this.editOk }
          onCancel={ this.editCancel }
          type={ this.state.editType }
          rowdata={ this.state.rowdata }
        />
        <SettingModule 
          visible={ this.state.settingVisible }
          roleList={ this.props.roleList }
          onClose={ this.onClose }
          rowdata={ this.state.rowdata }
        />
    	</div>
    )
  }
}

module.exports = ModuleName

// 新建编辑
class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      treeData: []
    }
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
    }
    if(nextProps.visible&&this.state.treeData.length <= 0){
      this.loadArea();
    }
  }

  loadArea = (treeNode)=>{
    var self = this;
    var selected = findRowData(this.state.treeData, treeNode?treeNode.props.eventKey:0, 'areaId');
    return new Promise((resolve) => {
      if(selected&&selected.children){
        resolve();
      }else{
        Ajax({
          url: '/area/list',
          data: {
            areaParentId: treeNode?treeNode.props.eventKey:0,
            perPage: 100
          },
          success: function(data){
            var treeData = self.state.treeData;
            if(treeNode&&self.state.treeData.length > 0){
              treeData = getNewTreeData(treeData, treeNode.props.eventKey, data.list, 'areaId');
            }else{
              treeData = data.list;
            }
            self.setState({
              treeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  handleCommit = () => {
    var self = this;
    self.props.form.validateFields((err, values) => {
      if(err == null&&!this.state.loading){
        self.setState({
          loading: true
        });
        const { type, rowdata, address  } = self.props;
        console.log(values);
        if(self.props.type == 'edit'){
          values.userId = rowdata.userId;
        }
        values.userType = 'typein';
        values.areaId = values.area&&values.area.areaName?values.area.areaId:undefined;
        Ajax({
          url: '/user/save',
          data: values,
          success: function(data){
            self.setState({
              loading: false
            });
            self.props.onOk(self.props.type, data);
          },
          error: function(error){
            self.setState({
              loading: false
            });
            message.error(error);
          }
        });
      }
    });
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onCancel();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const { visible, type, rowdata } = this.props;
    
    console.log(this.state.treeData);
    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""}>{loop(item.children)}</SelectTreeNode>;
      }
      console.log('isLeaf',item.children&&item.children.length == 0 );
      return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const treeNodes = loop(this.state.treeData);
    return (<Modal 
              title={ type == 'edit'?"修改用户信息":"新建用户" }
              visible={visible}
              onOk={ this.handleCommit } 
              onCancel={ this.onCancel }
              okText="确定" 
              cancelText="取消"
            >
              <Spin spinning={this.state.loading}>
                <Form
                  horizontal
                >
                  <Row gutter={20}>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="用户登录帐号">
                        {getFieldDecorator("userAccount",{
                          initialValue: type == 'edit'?rowdata.userAccount:"",
                          rules: [{
                            required: true, message: '请输入用户登录帐号',
                          }]
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="用户登录密码">
                        {getFieldDecorator("password",{
                          initialValue: ""
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={20}>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="用户名称">
                        {getFieldDecorator("userName",{
                          initialValue: type == 'edit'?rowdata.userName:"",
                          rules: [{
                            required: true, message: '请输入用户名称',
                          }]
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="所在区划">
                    {/*
                        {getFieldDecorator("areaId",{
                          initialValue: type == 'edit'?rowdata.areaId:"",
                          rules: [{
                            required: true, message: '请选择工作机构',
                          }]
                        })(
                            <TreeSelect
                              loadData={ this.loadArea }
                            >
                              { treeNodes }
                            </TreeSelect>
                        )}
                    */}
                        
                        {getFieldDecorator("area",{
                          initialValue: type == 'edit'?{areaId: rowdata.areaId+"", areaName: rowdata.areaName||rowdata.areaId}:{},
                          rules: [{ validator: validatorArea}],
                        })(
                          <AreaInput />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="联系电话">
                        {getFieldDecorator("phone",{
                          initialValue: type == 'edit'?rowdata.phone+"":""
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="身份证号码">
                        {getFieldDecorator("identityNumber",{
                          initialValue: type == 'edit'?rowdata.identityNumber+"":""
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="是否停用">
                        {getFieldDecorator("disabled",{
                          valuePropName: 'checked',
                          initialValue: type == 'edit'?rowdata.disabled:false
                        })(
                          <Checkbox />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={20} className="area-modifier">
                    <Col span={24}>
                      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="概述">
                        {getFieldDecorator("remark",{
                          initialValue: type == 'edit'?rowdata.remark:"",
                        })(
                          <Input type="textarea"/>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              </Spin>
            </Modal>);
  }
}
var EditModule = Form.create()(Edit);

// 设置角色
class Setting extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      roleList: []
    }
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
    }
    if(nextProps.visible&&nextProps.rowdata.userId != this.props.rowdata.userId){
      this.loadRoleList(nextProps.rowdata.userId);
      this.setState({
        roleList: []
      });
    }
  }

  loadRoleList = (id)=>{
    var self = this;
    self.setState({
      loading: true
    });
    Ajax({
      url: '/user/roleList',
      data: {
        userId: id
      },
      success: function(data){
        self.setState({
          roleList: _.map(data, 'roleId'),
          loading: false
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  handleCommit = () => {
    var self = this;
    self.props.form.validateFields((err, values) => {
      if(err == null&&!this.state.loading){
        self.setState({
          loading: true
        });
        const { rowdata  } = self.props;
        // console.log(values);
        values.roleIds = [values.roleIds]
        values.userId = rowdata.userId;
        Ajax({
          url: '/user/saveRole',
          data: values,
          success: function(data){
            self.setState({
              loading: false
            });
            message.success('修改记录成功！');
            self.props.onClose();
          },
          error: function(error){
            self.setState({
              loading: false
            });
            message.error(error);
          }
        });
      }
    });
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onClose();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { visible, rowdata } = this.props;

    var roleList = this.props.roleList||[];
    
    return (<Modal 
              title="修改用户角色"
              visible={ visible }
              onOk={ this.handleCommit } 
              onCancel={ this.onCancel }
              okText="确定" 
              cancelText="取消"
            >
              <Spin spinning={this.state.loading}>
                <Form
                  horizontal
                >
                  <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="角色" className="role-list">
                    {getFieldDecorator("roleIds",{
                      initialValue: this.state.roleList&&this.state.roleList.length>0?this.state.roleList[0]:"",
                    })(
                      <RadioGroup >
                        {
                          roleList.map((item)=>{
                            return <Radio key={item.id} value={item.id}>{item.roleName}</Radio>
                          })
                        }
                      </RadioGroup>
                    )}
                  </FormItem>
                </Form>
              </Spin>
            </Modal>);
  }
}
var SettingModule = Form.create()(Setting);
